﻿/***************************************************COPYRIGHT***************************************
* Copyright (c) 2008, Whiteboard-IT
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that 
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following 
 * disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the distribution.
*
* Neither the name of Whiteboard-IT, LLC nor the names of its contributors may be used to endorse or promote 
 * products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
*****************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Reflection;
using Boo.Lang;
using Castle.Core.Configuration;
using Castle.MicroKernel.Registration;
using Castle.Windsor.Configuration;
using Mite.Client;
using Mite.Configuration;
using Mite;
using Mite.MsSql;

namespace Mite.Client
{
	public class Program
	{
		public static void Main(string[] args)
		{
            if (args.Count() < 1)
            {
                Console.WriteLine("Options:");
                Console.WriteLine("TargetVersion=[targetversion] Environment=[environment] Version=[version] MigrationPath=[migrationpath]" );
                string tmp = Console.ReadLine();
                if (tmp != null) args = tmp.Split(' ');
            }
            var config = new MiteParameters(args);

			int? targetVersion = String.IsNullOrEmpty(config.TargetVersion) ? new int?() : int.Parse(config.TargetVersion);
			MigrationDirection direction = (MigrationDirection) Enum.Parse(typeof (MigrationDirection), config.Direction);
			string environment = config.Environment;
		    string filepath = "settings.boo";
			Console.WriteLine(String.Format("Environment: {0}\nDirection: {1}\nTarget: {2}\nMigrationDirectory:{3}", environment, direction, targetVersion, config.MigrationPath));
            

			Settings.Load(filepath);
			MiteEnvironment environment1 = Settings.GetEnvironment(environment);

			// TODO: Add support for multiple assemblies
			Assembly assembly = null;

			if (Settings.References.Count == 0)
			{
				// TODO: Do something more logical in this case such as load the assemblies from the config.MigrationDirectory
				assembly = Assembly.GetAssembly(typeof(Program));
			}
			else
			{
				assembly = Settings.References[0];
			}
            //Get the warnings and errors.  If warnings only then ask the user if they would like to continue
			/*
		    var mesgs = Migrator.GetWarningsAndErrors(environment1, targetVersion, config.MigrationPath);
            if (mesgs != null)
            {
                var fatals = mesgs.Where(mg => mg.IsFatal);
                if ( fatals != null)
                {
                    foreach (var msg in mesgs.OrderBy(mg => mg.IsFatal))
                        Console.WriteLine(msg.Message);
                    Console.WriteLine(
                        "ERROR:  There are fatal errors with one or more of your migration transformation.  The migration has not been executed.  (See above)");                   
                    return;
                }else
                {
                    Console.WriteLine("There is potential precision loss with one or more of your transformations (see above).  If you would like to continue please type 'y'");
                    if (Console.ReadLine() != "y")
                        return; //Don't continue if the precision loss is not ok'd
                }
            }*/
			Migrator.MigrateTo(environment1, targetVersion, config.MigrationPath);

			Console.ReadLine();
		}

	    #region Nested type: MiteParameters

		public class MiteParameters
		{
			public MiteParameters()
			{
				TargetVersion = null;
				Direction = "Up";
				Environment = "Development";
				MigrationPath = ".\\migration";
			}

			public MiteParameters(params string[] args)
				: this()
			{
				PropertyInfo[] properties = GetType().GetProperties();

				foreach (string arg in args)
				{
					if (arg.Contains("="))
					{
						string[] split = arg.Split('=');
						if (split.Length != 2)
							throw new ArgumentException("Invalid argument: " + arg);

						string propertyName = split[0];
						string value = split[1];

						PropertyInfo property = properties.SingleOrDefault(p => p.Name.Equals(propertyName));
						if (property == null)
							throw new ArgumentException(propertyName + " is not a valid argument.");
                        property.SetValue(this, Convert.ChangeType(value, property.PropertyType), null);
					}
					else
					{
						throw new ArgumentException("Invalid argument: " + arg);
					}
				}
			}

			/// <summary>
			/// Environment to run the migrations in.  Possible values include Production, Test, and Development.
			/// </summary>
			public string Environment { get; protected set; }
			public string TargetVersion { get; protected set; }
			public string Direction { get; protected set; }
			public string MigrationPath { get; protected set; }
            public string DatabaseName { get; protected set; }
		}

		#endregion
	}
}